package com.gxa.shop.servlet.order; /**
 * ${PACKAGE_NAME}
 * User: coma
 * Description:
 * Version: V1.0
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxa.shop.bean.pojo.OrderItems;
import com.gxa.shop.bean.pojo.Orders;
import com.gxa.shop.commons.r.R;

import com.gxa.shop.service.order.OrderService;
import com.gxa.shop.service.order.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "CreateOrderServlet", value = "/member/order")
public class CreateOrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        OrderService orderService = new OrderServiceImpl();
        StringBuilder jsonBuffer = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuffer.append(line);
        }

        // 解析 JSON 数据为 Orders 和 List<OrderItems> 对象
        JSONObject jsonData = JSON.parseObject(jsonBuffer.toString());

        if (jsonData.containsKey("goods")) {
            jsonData.put("orderItems", jsonData.getJSONArray("goods"));
            jsonData.remove("goods");
        }

        Orders orders = JSON.parseObject(jsonData.toJSONString(), Orders.class);
        List<OrderItems> orderItems = JSON.parseArray(jsonData.getJSONArray("orderItems").toJSONString(), OrderItems.class);

        // 调用服务层创建订单并接收返回的订单ID
        Integer orderId = orderService.createOrder(orders, orderItems);

        // 构建响应结果
        R result;
        if (orderId != null && orderId > 0) {
            result = R.ok("订单创建成功").addData("orderId", orderId);
        } else {
            result = R.error("订单创建失败");
        }

        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(result));
        writer.flush();
        writer.close();
    }
}
